﻿using NAudio.Wave;
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace TimeAlert
{
    public partial class Form1 : Form
    {
        private List<ExamDto> EXAM_LIST;
        private List<StageDto> STAGE_LIST;
        private DateTime START = DateTime.Now;
        private string Formate = "yyyy-MM-dd HH:mm:ss";

        delegate void SetTextCallBack(string text, Color color);
        private void SetText(string text, Color color)
        {
            if (this.rtbNext.InvokeRequired)
            {
                SetTextCallBack stcb = new SetTextCallBack(SetText);

                this.Invoke(stcb, new object[] { text, color });
            }
            else
            {
                this.rtbNext.AppendText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss\t") + text);
            }
        }

        private void SetExamText(string text, Color color)
        {
            if (this.rtbNext.InvokeRequired)
            {
                SetTextCallBack stcb = new SetTextCallBack(SetExamText);
                this.Invoke(stcb, new object[] { text, color });
            }
            else
            {
                this.rtbExam.AppendText(text);

                ChangeTextColorInUI(text, color);
            }
        }
        private string GetExamText(string text = "")
        {
            if (rtbExam.InvokeRequired)
            {
                // 如果不是在 UI 线程，使用 Invoke 执行该操作
                return (string)rtbExam.Invoke(new Func<string>(() => rtbExam.Text));
            }
            else
            {
                // 如果已经在 UI 线程，直接返回值
                return rtbExam.Text;
            }
        }
        private void ClearExamText(string x, Color color)
        {
            if (this.rtbExam.InvokeRequired)
            {
                SetTextCallBack stcb = new SetTextCallBack(ClearExamText);
                this.Invoke(stcb, new object[] { string.Empty, color });
            }
            else
            {
                this.rtbExam.Text = "";
            }
        }
        // 使用委托更改 RichTextBox 中的部分文字颜色
        private void ChangeTextColor(string textToFind, Color color)
        {
            if (rtbExam.InvokeRequired)
            {
                // 如果不是在 UI 线程，使用 Invoke 执行该操作
                rtbExam.Invoke(new Action<string, Color>((t, c) => ChangeTextColorInUI(t, c)), textToFind, color);
            }
            else
            {
                // 如果已经在 UI 线程，直接修改
                ChangeTextColorInUI(textToFind, color);
            }
        }

        // 在 UI 线程中改变 RichTextBox 中的文字颜色
        private void ChangeTextColorInUI(string textToFind, Color color)
        {
            ArrayList list = getIndexArray(this.rtbExam.Text, textToFind);
            if (list == null || list.Count == 0)
            {
                //MessageBox.Show(textToFind);
                //return;
            }
            for (int i = 0; i < list.Count; i++)
            {
                int index = (int)list[i];
                rtbExam.Select(index, textToFind.Length);
                rtbExam.SelectionColor = color;

            }
        }
        public Form1()
        {
            InitializeComponent();
            StartExam_Click(null, null);
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

        }
        private void button1_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "/sound/04_start_0.5.mp3";
            WaveOutEvent waveOut;
            Mp3FileReader mp3Reader;
            mp3Reader = new Mp3FileReader(path);
            waveOut = new WaveOutEvent();
            waveOut.Init(mp3Reader);
            waveOut.Play();
        }

        private void btnInitData_Click(object sender, EventArgs e)
        {
            DateTime start1 = DateTime.Now.AddSeconds(5);
            List<StageDto> stages1 = new List<StageDto>() {
                new StageDto() { Audio = "/sound/04_start_0.5.mp3", StartTime = start1.AddSeconds(1),Name="考试开始" } ,
                new StageDto { Audio = "/sound/05_end5min_0.6.mp3", StartTime = start1.AddSeconds(30),Name="离结束还有15分钟" },
                new StageDto { Audio = "/sound/06_ending_0.46.mp3", StartTime = start1.AddSeconds(60),Name="结束"},
            };
            ExamDto shuxue = new ExamDto() { StartTime = start1, EndTime = start1.AddHours(1), ExamName = "数学考试", StageList = stages1 };

            DateTime start = DateTime.Now.AddSeconds(35);
            List<StageDto> stages = new List<StageDto>() {
                new StageDto() { Audio = "/sound/04_start_0.5.mp3", StartTime = start.AddSeconds(1),Name="考试开始"  } ,
                new StageDto (){ Audio = "/sound/05_end5min_0.6.mp3", StartTime = start.AddSeconds(30),Name="离结束还有15分钟"  },
                new StageDto (){ Audio = "/sound/06_ending_0.46.mp3", StartTime = start.AddSeconds(60),Name="结束"  },
            };
            ExamDto yuwen = new ExamDto() { StartTime = start, EndTime = start.AddHours(1), ExamName = "语文考试", StageList = stages };

            List<ExamDto> result = new List<ExamDto>() { yuwen, shuxue };
            File.WriteAllText(Application.StartupPath + "/Config.json", JsonConvert.SerializeObject(result));

            EXAM_LIST = result;
            STAGE_LIST = EXAM_LIST.SelectMany(x => x.StageList).Where(x => DateTime.Now <= x.StartTime).ToList();
        }
        private void StartExam_Click(object sender, EventArgs e)
        {
            SetText("程序启动\n", Color.Black);
            string text = File.ReadAllText(Application.StartupPath + "/Config.json");
            EXAM_LIST = JsonConvert.DeserializeObject<List<ExamDto>>(text);
            STAGE_LIST = EXAM_LIST.SelectMany(x => x.StageList).Where(x => DateTime.Now <= x.StartTime).ToList();
            UdateExam(null, null);
            Thread.Sleep(5);
            ChangeExamColor(null, null);

            System.Timers.Timer timer2 = new System.Timers.Timer();
            timer2.Enabled = true;
            timer2.Interval = 10000; //执行间隔时间，单位为毫秒；
            timer2.Start();
            timer2.Elapsed += new System.Timers.ElapsedEventHandler(UdateExam);

            //System.Timers.Timer timer3 = new System.Timers.Timer();
            //timer3.Enabled = true;
            //timer3.Interval = 1010; //执行间隔时间，单位为毫秒；
            //timer3.Start();
            //timer3.Elapsed += new System.Timers.ElapsedEventHandler(ChangeExamColor);

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Enabled = true;
            timer.Interval = 1000; //执行间隔时间，单位为毫秒；
            timer.Start();
            timer.Elapsed += new System.Timers.ElapsedEventHandler(StartExam);
        }

        private void StartExam(object sender, EventArgs e)
        {
            var exams = STAGE_LIST.FindAll(x => AreDatesEqual(x.StartTime, DateTime.Now));
            exams.ForEach(x =>
            {
                SetText(x.StartTime + "\t" + x.Name + "\n", Color.Black);
                string path = Application.StartupPath + x.Audio;

                Mp3FileReader mp3Reader = new Mp3FileReader(path);
                WaveOutEvent waveOut = new WaveOutEvent();
                waveOut.Init(mp3Reader);
                waveOut.Play();
            });
        }
        private void ChangeExamColor(object sender1, EventArgs e1)
        {
            EXAM_LIST.ForEach(e =>
            {
                foreach (var s in e.StageList)
                {
                    string str = "\t" + s.StartTime.ToString(Formate) + "\t" + s.Name + "\n";
                    Color color = START > s.StartTime ? Color.Red : (s.StartTime < DateTime.Now ? Color.Gray : Color.Green);
                    // 红色表示已经过期，灰色表示程序已经执行，绿色表示程序将要执行
                    ChangeTextColor(str, color);
                }
            });
        }
        private void UdateExam(object sender1, EventArgs e1)
        {
            ClearExamText("", Color.Black);
            EXAM_LIST.ForEach(e =>
            {
                SetExamText(e.ExamName + "\n", Color.Black);
                foreach (var s in e.StageList)
                {
                    string str = "\t" + s.StartTime.ToString(Formate) + "\t" + s.Name + "\n";
                    SetExamText(str, START > s.StartTime ? Color.Red : (s.StartTime < DateTime.Now ? Color.Gray : Color.Green));
                    // 红色表示已经过期，灰色表示程序已经执行，绿色表示程序将要执行
                    //ChangeTextColor("\t2025-06-20 00:51:49\t离结束还有15分钟\n", Color.Green);
                }
            });
        }

        // 获取指定字符串在文本中的所有索引
        public ArrayList getIndexArray(String inputStr, String findStr)
        {
            ArrayList list = new ArrayList();
            int start = 0;
            while (start < inputStr.Length)
            {
                int index = inputStr.IndexOf(findStr, start);
                if (index >= 0)
                {
                    list.Add(index);
                    start = index + findStr.Length;
                }
                else
                {
                    break;
                }
            }
            return list;
        }

        bool AreDatesEqual(DateTime dt1, DateTime dt2)
        {
            // 比较年月日、时分秒是否一致
            return dt1.Year == dt2.Year &&
                   dt1.Month == dt2.Month &&
                   dt1.Day == dt2.Day &&
                   dt1.Hour == dt2.Hour &&
                   dt1.Minute == dt2.Minute &&
                   dt1.Second == dt2.Second;
        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            SettingForm settingForm = new SettingForm();
            settingForm.Owner = this;
            settingForm.ShowDialog();
        }
    }

}
